<template>
  <div>
    <!-- 总体概述 -->
    <ShipmentDetailScreen
      :data="data"
      @changeTransientStatus="getShipmentData"
      @holdCompleteDelivery="holdCompleteDelivery"
      @showRegistration="showRegistration"
    />
    <!-- <h1 @click="changeShipmentCompleted">模拟发货按钮</h1> -->
    <!-- <h1 @click="inspectCodeNum('0022')">模拟增加</h1> -->
    <!-- 货源信息 -->
    <div
      v-if="data.deliverCargoWaybills && data.deliverCargoWaybills.length > 0"
    >
      <ShipmentDetailItem
        v-for="(item, index) in data.deliverCargoWaybills"
        :key="index"
        :data="item"
        :index="index"
        :isEdit="isEdit"
        @changeDamageDetailsEdit="changeDamageDetailsEdit"
        @changeValue="codeChangeNum2"
      />
    </div>
    <!-- 新增破损登记 -->
    <DamageDetailsEdit
      :propsData="data"
      @addDamageInfos="addDamageInfos"
      type1="0"
      ref="DamageDetailsEdit"
    />
    <!-- 出货口内容 -->
    <van-popup v-model="show" position="bottom" round>
      <van-picker
        title="请选择出货口"
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="show = false"
      />
    </van-popup>
    <!-- 弹窗 -->
    <van-popup v-model="show1" round position="bottom">
      <h1 class="popupTitle">
        <p class="back" @click="show1 = false">返回</p>
        <p>请选择对应的主单号</p>
        <p class="ok" @click="codeChangeNum1">确定</p>
      </h1>
      <van-radio-group v-model="radio" @change="checkRadio">
        <van-cell-group>
          <van-cell
            v-for="(item, index) in repeatList"
            :key="index"
            :title="item.masterWaybill"
            clickable
          >
            <template #right-icon>
              <van-radio :name="index" checked-color="#f29d12" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </van-popup>
  </div>
</template>

<script>
import {
  getShipmentData,
  shipmentCompleted,
  getExportCargo,
  deliverNumAddType,
  holdCompleteDelivery,
} from "@/services/api";
import Vue from "vue";
import ShipmentDetailScreen from "@/components/ShipmentDetailScreen";
import ShipmentDetailItem from "@/components/ShipmentDetailItem";
import DamageDetailsEdit from "@/components/DamageDetailsEdit";
import { Toast, Picker, Popup, Cell, CellGroup, RadioGroup, Radio } from "vant";
Vue.use(Radio);
Vue.use(RadioGroup);
Vue.use(Cell);
Vue.use(CellGroup);
Vue.use(Picker);
Vue.use(Popup);
export default {
  data() {
    return {
      data: {},
      arryObj: [],
      columns: [],
      show: false,
      show1: false,
      exportCargoList: [],
      isEdit: true,
      repeatList: [],
      radio: 0,
    };
  },
  created() {
    this.getShipmentData();
    this.getExportCargo();
    this.deliverNumAddType();
  },
  mounted() {
    // 回调
    window["scan_data"] = (e) => {
      this.inspectCodeNum(e);
    };
    // 发货完成原生回调
    window["customClick"] = () => {
      this.changeShipmentCompleted();
    };
    // 设置按钮
    setTimeout(() => {
      try {
        window.appPlat.setRightTitle("发货完成");
      } catch (e) {
        Toast("设置未成功");
      }
    }, 200);
  },
  methods: {
    // 获取数据
    getShipmentData() {
      getShipmentData({ deliverCargoBillId: this.$route.params.id }).then(
        (res) => {
          this.data = res;
        }
      );
    },
    // 根据扫描增加数量
    codeChangeNum(code) {
      let isBoot = true;
      this.data.deliverCargoWaybills.map((item, index) => {
        if (
          item.masterWaybill
            .replace(/-/g, "")
            .startsWith(code.replace(/-/g, "").slice(0, 11)) ||
          item.masterWaybill.replace(/-/g, "") == code.replace(/-/g, "")
        ) {
          if (
            item.subDeliverCargoWaybills &&
            item.subDeliverCargoWaybills.length > 0
          ) {
            Toast("请直接扫描分单号");
            isBoot = false;
            return;
          }
          item.actualNum = item.actualNum ? (item.actualNum += 1) : 1;
          document.getElementById("a" + index).scrollIntoView();
          isBoot = false;
        } else {
          item.subDeliverCargoWaybills &&
            item.subDeliverCargoWaybills.map((item1, index1) => {
              if (
                item1.subWaybill.replace(/-/g, "") == code.replace(/-/g, "")
              ) {
                item1.actualNum = item1.actualNum ? (item1.actualNum += 1) : 1;
                item.actualNum = item.actualNum ? (item.actualNum += 1) : 1;
                document.getElementById("a" + index + index1).scrollIntoView();
                isBoot = false;
              }
            });
        }
      });
      if (isBoot) {
        Toast("没有匹配的数据");
      }
    },
    // 检查数据有无重复子订单号
    inspectCodeNum(code) {
      const arry = [];
      this.data.deliverCargoWaybills.map((item) => {
        item.subDeliverCargoWaybills &&
          item.subDeliverCargoWaybills.map((item1) => {
            if (item1.subWaybill.replace(/-/g, "") == code.replace(/-/g, "")) {
              arry.push({
                masterWaybill: item.masterWaybill,
                subWaybill: item1.subWaybill,
              });
            }
          });
      });
      if (arry.length > 1) {
        this.repeatList = arry;
        this.show1 = true;
      } else {
        this.codeChangeNum(code);
      }
    },
    // 子父订单筛选
    codeChangeNum1() {
      let isBoot = true;
      this.data.deliverCargoWaybills.map((item, index) => {
        if (
          item.masterWaybill
            .replace(/-/g, "")
            .startsWith(
              this.repeatList[this.radio].masterWaybill
                .replace(/-/g, "")
                .slice(0, 11)
            ) ||
          item.masterWaybill.replace(/-/g, "") ==
            this.repeatList[this.radio].masterWaybill.replace(/-/g, "")
        ) {
          item.subDeliverCargoWaybills &&
            item.subDeliverCargoWaybills.map((item1, index1) => {
              if (
                item1.subWaybill.replace(/-/g, "") ==
                this.repeatList[this.radio].subWaybill.replace(/-/g, "")
              ) {
                item1.actualNum = item1.actualNum ? (item1.actualNum += 1) : 1;
                item.actualNum = item.actualNum ? (item.actualNum += 1) : 1;
                document.getElementById("a" + index + index1).scrollIntoView();
                isBoot = false;
              }
            });
        }
      });
      if (isBoot) {
        Toast("没有匹配的数据");
      }
      this.show1 = false;
    },
    // 手动添加
    codeChangeNum2(data) {
      this.data.deliverCargoWaybills.map((item) => {
        if (
          item.masterWaybill
            .replace(/-/g, "")
            .startsWith(data.masterWaybill.replace(/-/g, "").slice(0, 11)) ||
          item.masterWaybill.replace(/-/g, "") ==
            data.masterWaybill.replace(/-/g, "")
        ) {
          item.subDeliverCargoWaybills &&
            item.subDeliverCargoWaybills.map((item1) => {
              if (
                item1.subWaybill.replace(/-/g, "") ==
                data.subWaybill.replace(/-/g, "")
              ) {
                item1.actualNum = item1.actualNum
                  ? data.type == "+"
                    ? (item1.actualNum += 1)
                    : (item1.actualNum -= 1)
                  : 1;
                item.actualNum = item.actualNum
                  ? data.type == "+"
                    ? (item.actualNum += 1)
                    : (item.actualNum -= 1)
                  : 1;
              }
            });
        }
      });
    },
    // 选择主单号对应的子单号
    checkRadio(e) {
      this.radio = e;
    },
    // 发货计算
    shipmentRecursion(arr) {
      let arryObj = [];
      if (!Array.isArray(arr)) {
        return [];
      }
      arr.map((item) => {
        arryObj.push({
          actualDeliverGoodsNum: item.actualNum,
          deliverCargoWaybillId: item.id,
        });
        if (
          item.subDeliverCargoWaybills &&
          item.subDeliverCargoWaybills.length > 0
        ) {
          item.subDeliverCargoWaybills.map((item) => {
            arryObj.push({
              actualDeliverGoodsNum: item.actualNum,
              deliverCargoWaybillId: item.id,
            });
          });
        }
      });
      return arryObj;
    },
    // 判断发货数量是不是与实际发货数量相等
    shipmentRecursion1(arr) {
      let boot = true;
      if (!Array.isArray(arr)) {
        return [];
      }
      arr.map((item) => {
        if (item.consigneeNum != item.actualNum) {
          boot = false;
        }
        item.subDeliverCargoWaybills &&
          item.subDeliverCargoWaybills.length > 0 &&
          this.shipmentRecursion1(item.subDeliverCargoWaybills);
      });
      return boot;
    },
    // 获取发货口数据
    getExportCargo() {
      getExportCargo().then((res) => {
        if (res) {
          this.exportCargoList = res;
          this.columns = res.map((item) => item.name);
        }
      });
    },
    // 完成发货
    changeShipmentCompleted() {
      if (!this.shipmentRecursion1(this.data.deliverCargoWaybills)) {
        Toast("实际发货件数与应该件数须一致");
        return;
      }
      this.show = true;
    },
    // 新增破损
    addDamageInfos(e) {
      if (e.masterWaybill != "" && e.subWaybill != "") {
        this.data.deliverCargoWaybills.map((item) => {
          if (
            item.masterWaybill
              .replace(/-/g, "")
              .startsWith(e.masterWaybill.replace(/-/g, "").slice(0, 11))
          ) {
            item.subDeliverCargoWaybills &&
              item.subDeliverCargoWaybills.map((item1) => {
                if (item1.subWaybill == e.subWaybill) {
                  if (item1.damageInfos.length > 0) {
                    item1.damageInfos[0].damageNum = e.damageNum;
                  } else {
                    item1.damageInfos.push({
                      damageNum: e.damageNum,
                      id: e.id,
                    });
                  }
                }
              });
          }
        });
      } else {
        this.data.deliverCargoWaybills.map((item) => {
          if (
            item.masterWaybill
              .replace(/-/g, "")
              .startsWith(e.masterWaybill.replace(/-/g, "").slice(0, 11)) ||
            item.masterWaybill.replace(/-/g, "") ==
              e.masterWaybill.replace(/-/g, "")
          ) {
            if (item.damageInfos.length > 0) {
              item.damageInfos[0].damageNum = e.damageNum;
            } else {
              item.damageInfos.push({ damageNum: e.damageNum, id: e.id });
            }
          }
        });
      }
    },
    // 确定发货
    onConfirm(e, index) {
      shipmentCompleted({
        cargoWaybillDeliveries: this.shipmentRecursion(
          this.data.deliverCargoWaybills
        ),
        deliverCargoBillId: this.data.id,
        deliverCargoNo: this.data.deliverCargoNo,
        export: this.exportCargoList[index].value,
      }).then((res) => {
        if (res.status) {
          Toast(res.message);
        } else {
          try {
            window.appPlat.finish();
          } catch (e) {
            this.$router.go(-1);
          }
        }
      });
    },
    // 暂存发货
    holdCompleteDelivery() {
      holdCompleteDelivery({
        cargoWaybillDeliveries: this.shipmentRecursion(
          this.data.deliverCargoWaybills
        ),
        deliverCargoBillId: this.data.id,
        deliverCargoNo: this.data.deliverCargoNo,
      }).then((res) => {
        if (res) {
          Toast("暂存发货成功");
        }
      });
    },
    // 开启破损登记
    showRegistration() {
      this.$refs.DamageDetailsEdit.show = true;
    },
    // 子组件传值编辑
    changeDamageDetailsEdit(e) {
      this.$refs.DamageDetailsEdit.getDamageInfo(e);
    },
    // 检查是否可以加减
    deliverNumAddType() {
      deliverNumAddType().then((res) => {
        if (res) {
          if (res.value == 1) {
            this.isEdit = true;
          } else {
            this.isEdit = false;
          }
        }
      });
    },
  },
  components: {
    ShipmentDetailScreen,
    ShipmentDetailItem,
    DamageDetailsEdit,
  },
};
</script>

<style lang="scss" scoped>
.popupTitle {
  width: 100%;
  font-size: 18px;
  color: #333;
  text-align: center;
  line-height: 45px;
  display: flex;
  justify-content: space-between;
  padding: 0 15px;
  box-sizing: border-box;
  border-bottom: 1px solid #f5f5f5;
  .back {
    color: #666;
  }
  .ok {
    color: #f39d11;
  }
}
</style>
